package com.woniuxy.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.common.utils.CRC64;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniuxy.commons.model.Result;
import com.woniuxy.commons.utils.CommonsUtil;
import com.woniuxy.commons.utils.DateUtil;
import com.woniuxy.commons.utils.OrderLogUtil;
import com.woniuxy.commons.utils.OssTemplate;
import com.woniuxy.controller.form.*;
import com.woniuxy.service.CommentAttachmentService;
import com.woniuxy.service.CommentInfoService;
import com.woniuxy.service.dto.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author psy
 * @since 2022-06-28
 */
@RestController
@RequestMapping("/commentInfo")
@Api(tags = "评价接口")
public class CommentInfoController {
    @Resource
    private CommentInfoService commentInfoService;
    @Resource
    private RedisTemplate<String,String> sot;
    @Resource
    private CommentAttachmentService commentAttachmentService;
    /**
     * 买家评价
     * @param caaf 接收前端传递的评价表和评价附件表信息
     * @return
     */
    @PostMapping("/buycomment")
    @ApiOperation("买家评价")
    public Result buyComment(@RequestBody CommentAndAttentForm caaf){
        CommentCreatForm commentCreatForm = caaf.getCommentCreatForm();
        System.out.println(caaf.getCommentAttent());
        //新增评价表
        sot.delete(commentCreatForm.getStoreId()+"DD"+commentCreatForm.getOrderNum());
        UserDetailsDto userDetailsDto = (UserDetailsDto) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        commentCreatForm.setReplay("无");
        commentCreatForm.setUserPhoto(userDetailsDto.getPhoto());
        commentCreatForm.setUserName(userDetailsDto.getUsername());
        commentCreatForm.setUser(userDetailsDto.getUsername());
        commentCreatForm.setDate(CommonsUtil.getOrderCreateTime());
        commentCreatForm.setDeleted(0);
        commentCreatForm.setReplayFlag(0);
        boolean b = commentInfoService.addComment(commentCreatForm);
        //新增评价附件表
        if(commentCreatForm.getPictureFlag()==1){
            Long id = commentInfoService.getId(commentCreatForm.getOrderNum());
            ArrayList<CommentAttentCreateForm> commentAttent = caaf.getCommentAttent();
            for (CommentAttentCreateForm commentAttentCreateForm : commentAttent) {
                commentAttentCreateForm.setCommentId(id);
                boolean b1 = commentAttachmentService.addCommentAttach(commentAttentCreateForm);
            }
            System.out.println(commentAttent);
        }
        return Result.success(200,"新增评价表和评价附件表成功",null);
    }

    /**
     * 买家上传评价图片
     * @param images 买家上传的图片文件
     * @return
     * @throws IOException
     */
    @PostMapping("/commentphoto")
    @ApiOperation("买家上传评价图片")
    public Result commentPhoto(MultipartFile[] images) throws IOException {
        System.out.println(images);
        ArrayList<CommentAttentCreateDto> commentAttents=new ArrayList<>();
        for (int i = 0; i < images.length; i++) {
            System.out.println(images[i]);
            String oldName = images[i].getOriginalFilename();
            String s = OssTemplate.fileUpload("img/"+oldName,images[i].getInputStream(), "woniu-75-3");
            long size = images[i].getSize();
            String fileSuffix = oldName.substring(oldName.lastIndexOf(".") + 1, oldName.length());
            String filePath=s;
            String fileName=s;
            //返回URL，前端调用显示
            CommentAttentCreateDto commentAttent = OrderLogUtil.createCommentAttent(oldName, fileName, size, filePath, fileSuffix);
            commentAttents.add(commentAttent);
        }
        return Result.success(200,"文件上传成功",commentAttents);
    }

    /**
     * 商家回复评价
     * @param storeReplyForm
     * @return
     */
    @PostMapping("/replay")
    @ApiOperation("商家回复评价")
    public Result replay(@RequestBody StoreReplyForm storeReplyForm){
        storeReplyForm.setReplayFlag(1);
        System.out.println(storeReplyForm);
        boolean replay = commentInfoService.replay(storeReplyForm);
        return Result.success(200,"商家回复成功",null);
    }

    /**
     * 买家删除评价
     * @param id 接收前端传递的评价ID
     * @return
     */
    @DeleteMapping("/delcomment")
    @ApiOperation("买家删除评价")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "前端传递的评价ID")
    })
    public Result delComment(Long id){
        boolean b = commentInfoService.delComment(id);
        return Result.success(200,"用户删除成功",null);
    }

    /**
     * 商家查看所有评价（根据商家ID）
     * @param pageNum 当前页
     * @param pageSize 每页数量
     * @param replay 查询未回复评价的标识，0表示查询，其他值表示查询全部
     * @return 返回评价信息
     */
    @GetMapping("/getcommentbystoreid")
    @ApiOperation("商家查看评价（根据商家ID）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum",value = "当前页"),
            @ApiImplicitParam(name = "pageSize",value = "每页数量"),
            @ApiImplicitParam(name = "replay",value = "查询未回复评价的标识，0表示查询，其他值表示查询全部")
    })
    public Result getCommentByStoreId(Integer pageNum,Integer pageSize,Integer replay){
        UserDetailsDto userDetailsDto = (UserDetailsDto) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Long id = userDetailsDto.getId();
        //查询未回复的订单
        if(replay==0){
            Page<CommentStoreDto> commentStoreNotReplay = commentInfoService.getCommentStoreNotReplay(id, pageNum, pageSize);
            return Result.success(200,"加载商家店铺评价成功",commentStoreNotReplay);
        }else{

            Page<CommentStoreDto> commentByStoreId = commentInfoService.getCommentByStoreId(id, pageNum, pageSize);
            return Result.success(200,"加载商家店铺评价成功",commentByStoreId);
        }

    }
    /**
     * 商家点击对应有图片的评价，展开其图片
     * @param commentId 评价ID
     * @return 返回图片Url集合
     */
    @GetMapping("/getcommentattent")
    @ApiOperation("商家点击对应有图片的评价，展开其图片")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "commentId",value = "评价ID")
    })
    public Result getCommentAttent(Long commentId){
        ArrayList<String> commentAttent = commentAttachmentService.getCommentAttent(commentId);
        return Result.success(200,"加载对应评价的图片成功",commentAttent);
    }

    /**
     * 商家店铺界面的评价展示（支持通过满意度、有无图片进行分类查询）
     * @param commentStoreShowForm
     * @return 返回评价信息
     */
    @GetMapping("/getcommentsinstore")
    @ApiOperation("商家店铺界面的评价展示（支持通过满意度、有无图片进行分类查询）")
    public Result getCommentsInStore(CommentStoreShowForm commentStoreShowForm){
        StoreShowCommentDto commentsInStore = commentInfoService.getCommentsInStore(commentStoreShowForm);
        List<CommentsStoreShowDto> records = commentsInStore.getCommentsStoreShowDtoPage().getRecords();
        for (CommentsStoreShowDto record : records) {
            String orderDate = record.getOrderDate();
            String reachDate = record.getReachDate();
            Long orderdate = DateUtil.parseDateString(orderDate, "yyyy-MM-dd HH:mm:ss");
            Long reachdate = DateUtil.parseDateString(reachDate, "yyyy-MM-dd HH:mm:ss");
            String time=Math.ceil((reachdate-orderdate)/60000)+"分钟";
            record.setTime(time);
        }
        return Result.success(200,"加载评价信息成功",commentsInStore);
    }
    /**
     * 买家查看或者卖家查看评价（根据订单编号），返回图片Url集合
     * @param orderNum 订单编号
     * @return 返回对应的评价信息
     */
    @GetMapping("/getcommentbyordernum")
    @ApiOperation("买家查看或者卖家查看评价（根据订单编号)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderNum",value = "订单编号")
    })
    public Result getCommentByOrderNum(String orderNum){
        CommentByOrderNumDto commentByOrderNum = commentInfoService.getCommentByOrderNum(orderNum);
        System.out.println(commentByOrderNum);
        return Result.success(200,"加载订单对应评价成功",commentByOrderNum);
    }

    /**
     * 商家评分(综合商家评分、菜品评分、配送评分计算，存到redis)
     * @param storeId 商家ID
     * @param updateFlag 是否更新评分的标识
     * @return 返回评分信息对象
     * @throws JsonProcessingException
     */
    @GetMapping("/getstorescore")
    @ApiOperation("商家评分展示(综合商家评分、菜品评分、配送评分计算)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "storeId",value = "商家ID"),
            @ApiImplicitParam(name = "updateFlag",value = "更新标识")
    })
    public Result getStoreScore(Long storeId,Integer updateFlag) throws JsonProcessingException {
        if(null==updateFlag||updateFlag==0){
            String storeScore = (String)sot.opsForValue().get(storeId+"score");
            ScoreStoreDto scoreStoreDto = JSON.parseObject(storeScore, ScoreStoreDto.class);
            System.out.println(scoreStoreDto);
            return Result.success(200,"商家评分加载成功",scoreStoreDto);
        }else {
            ScoreStoreDto storeScore = commentInfoService.getStoreScore(storeId);
            System.out.println(storeScore);
            ObjectMapper om=new ObjectMapper();
            String s = om.writeValueAsString(storeScore);
            sot.opsForValue().set(storeId+"score",s);
            return Result.success(200,"商家评分加载成功",storeScore);
        }

    }

    /**
     * 评价统计（支持时间段查询、模糊查询、分类查询）
     * @param commentStaticForm 接收前端传递的参数
     * @return 返回评价数据和对应的评价列表
     */
    @GetMapping("/commentstatic")
    @ApiOperation("评价统计（支持时间段查询、模糊查询、分类查询）")
    public Result commentStatic(CommentStaticForm commentStaticForm){
        System.out.println("==================");
        System.out.println(commentStaticForm.getStartTime()+""+commentStaticForm.getEndTime());
        CommentStaticDto commentStaticDto = commentInfoService.commentStatic(commentStaticForm);
        System.out.println(commentStaticDto);
        return Result.success(200,"加载评价统计成功",commentStaticDto);

    }

}

